#!/usr/bin/env python
# coding:utf-8
# Author: mingzhong.huang

import json
import requests
from datetime import datetime
import pandas as pd
from pprint import pprint
from core.logger import logger
from setting import config


class SaPlatform():
    def __init__(self):
        self.url = config.SA_API
        self.token = config.SA_TOKEN
        self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
        self.headers = {
            "User-Agent": self.user_agent, "Connection": "keep-alive",
            "Content-Type": "application/json",
            "authorization": self.token
        }


    def get_work_orders_month(self, bill_cycle: str):
        """
        获取一个月的工单列表
        """
        year = int(bill_cycle.split("-")[0])
        month = int(bill_cycle.split("-")[1])
        url = self.url + f"/api/aliyun/gaap/check/resource?year={year}&month={month}"
        try:
            req = requests.get(url=url, headers=self.headers)
            if req.status_code != 200:
                logger.error(f"get work orders for month failed")
                return False
            work_orders = json.loads(req.text)
        except Exception as e:
            logger.error(f"get work orders for month error =>{e}")
            return False

        logger.info(f"get work orders for month success")
        return work_orders



    def get_work_order_one(self, workorder: int):
        """
        获取一个工单信息
        """
        url = self.url + f"/api/workorder/tickets?page=1&per_page=15&sort=-created_on&category_name=&search={workorder}&all=true"
        try:
            req = requests.get(url=url, headers=self.headers)
            if req.status_code != 200:
                logger.error(f"get ont work order:{workorder} failed")
                return False
            work_order = json.loads(req.text)
        except Exception as e:
            logger.error(f"get ont work order:{workorder} error =>{e}")
            return False

        logger.info(f"get ont work order:{workorder} success")
        return work_order
    
    
    
    def get_cloud_platform(self, work_order_info: str):
        for field in work_order_info["values"]:
            if field["name"] == "所属账号":
                if field["value"] in ["卫盈联主账号", "天冕walletgugu账号", "天冕虚拟银行账号", "卫盈联welabfintech账号", "天冕tianmianlab账号", "卫盈联welabconsfin账号"]:
                    return "阿里云"
                
                if field["value"] in ["华为welabcloud账号", "华为tianmiantech账号"]:
                    return "华为云"
                return "无"
                
        return "无"
    
    
    
    
    def get_info_items(self, value):
        try:
            if value.startswith("["):
                # 替换单引号为双引号
                value = value.replace("'", "\"")

                # 解析为 JSON 对象
                result = json.loads(value)
            else:
                result = value.strip().split()
        except Exception as e:
            logger.error(f"get info items:{value} error =>{e}")
            result = []
            
        return result

    
    
    def get_event_info(self, work_order_info: str):
        event_info = {
            "info_type": "无",
            "info_items": []
        }
        if work_order_info["subname"] in [
            "云服务器ECS回收",
            "云服务器ECS变更",
            "云服务器ECS申请",
            "elasticsearch变更",
            "elasticsearch申请",
            "云图数据库变更",
            "云图数据库申请",
            "云数据库kafka申请",
            "云数据库kafka回收",
            "云数据库MongoDB变更",
            "云数据库MongoDB申请",
            "云数据库PolarDB申请",
            "云数据库RDS申请",
            "云数据库Redis变更",
            "云数据库Redis申请"
        ]:
            event_info["info_type"] = "实例名称"
            event_info["info_items"] = self.get_info_items(work_order_info["values"][1]["value"])
            
        elif work_order_info["subname"] in [
            "elasticsearch回收",
            "云图数据库回收",
            "云数据库MongoDB回收",
            "云数据库PolarDB变更",
            "云数据库PolarDB回收",
            "云数据库RDS变更",
            "云数据库RDS回收",
            "云数据库Redis回收"
        ]:
            event_info["info_type"] = "实例id",
            event_info["info_items"] = self.get_info_items(work_order_info["values"][1]["value"])
                
        return event_info
    

    
    
    def get_work_order_infos(self, bill_cycle: str):
        work_order_infos = []
        work_orders = self.get_work_orders_month(bill_cycle)
        work_order_items = work_orders["data"]["details"]["create_items"] + work_orders["data"]["details"]["degrade_items"] + work_orders["data"]["details"]["recovery_items"] + work_orders["data"]["details"]["upgrade_items"]
        for work_order in work_order_items:
            work_order_info = self.get_work_order_one(work_order["workorder_ticket_id"])
            if not work_order_info or len(work_order_info["data"]["items"])==0:
                logger.error(f"get ont work order failed, continue")
                continue
            
            work_order_info = work_order_info["data"]["items"][0]
            event_info = self.get_event_info(work_order_info)
            data = {
                "name": work_order_info["title"],
                "bill_cycle": bill_cycle,
                "cloud_platform": self.get_cloud_platform(work_order_info),
                "event_type": "工单事件",
                "relation_id": work_order_info["id"],
                "info_type": event_info["info_type"],
                "info_items": event_info["info_items"],
                "comment": work_order_info["values"][-1]["value"][:255]
            }
            
            work_order_infos.append(data)
        
        return work_order_infos
        



def main():
    sa_platform = SaPlatform()
    # work_orders_info = sa_platform.get_work_order_infos("2023-02")
    # work_order_info = sa_platform.get_work_order_one(43919)
    # work_order_info = work_order_info["data"]["items"][0]
    # event_info = sa_platform.get_event_info(work_order_info)
    
    # pprint(event_info)
    
    # content = """
    # 告警标题：blacklist服务定时任务监控UserTypeInfoConsumer
    # 时间区间：17:50:00~17:55:00
    # 告警条件：07:00:00~23:00:00 && `count` > 1
    # 告警通知：eric.lv,qianfeng.zhou
    # blacklist => 653
    # """
    # data = {'msgtype': 'text', 'text':{'content': content}}
    # #res = requests.post('https://sa.welab-inc.com/api/callbacks/falcon/prod/biz_wechat', data=data)
    # res = requests.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=632a548c-13af-4442-a67c-7e14234de7d0', data=json.dumps(data))
    # return res.text
    
    return True

        


if __name__ == "__main__":
    main()

















    # 作废的代码
    # def get_containers(self):
    #     """
    #     获取容器信息
    #     """
    #     url = self.url + "/api/aliyun/containers"
    #     try:
    #         req = requests.get(url=url, headers=self.headers)
    #         if req.status_code != 200:
    #             logger.error(f"get containers failed")
    #             return False
    #         containers_info = json.loads(req.text)
    #     except Exception as e:
    #         logger.error(f"get containers error =>{e}")
    #         return False

    #     logger.info(f"get containers success")
    #     return containers_info


    # def get_department_ratio(self):
    #     """
    #     获取k8s集群各部门资源的使用百分比
    #     """
    #     containers_info = self.get_containers()
    #     df_containers = pd.DataFrame(containers_info["data"])
    #     group_data = df_containers.groupby(["depart_name"]).agg({"cpu_spec": "sum", "mem_spec": "sum"}).to_dict()
    #     department_info = {}

    #     # 统计cpu信息
    #     total_cpu = 0
    #     for depart_name, cpu in group_data["cpu_spec"].items():
    #         if depart_name == "": continue

    #         # if depart_name == "天冕科技": depart_name = "云平台"

    #         cpu = round(cpu, 2)
    #         if depart_name not in department_info:
    #             department_info[depart_name] = {
    #                 "name": depart_name,
    #                 "cpu": cpu
    #             }
    #         else:
    #             if "cpu" not in department_info[depart_name]:
    #                 department_info[depart_name]["cpu"] = cpu
    #             else:
    #                 department_info[depart_name]["cpu"] += cpu

    #         total_cpu += cpu

    #     # 统计mem信息
    #     total_mem = 0
    #     for depart_name, mem in group_data["mem_spec"].items():
    #         if depart_name == "": continue

    #         # if depart_name == "天冕科技": depart_name = "云平台"

    #         mem = round(mem, 2)
    #         if depart_name not in department_info:
    #             department_info[depart_name] = {
    #                 "name": depart_name,
    #                 "mem": mem
    #             }
    #         else:
    #             if "mem" not in department_info[depart_name]:
    #                 department_info[depart_name]["mem"] = mem
    #             else:
    #                 department_info[depart_name]["mem"] += mem

    #         total_mem += mem

    #     # 组装部门信息
    #     departs_info =  []
    #     for depart_name, depart_info in department_info.items():
    #         depart_info["cpu_ratio"] = round(depart_info["cpu"] / total_cpu * 100, 2)
    #         depart_info["mem_ratio"] = round(depart_info["mem"] / total_mem * 100, 2)
    #         departs_info.append(depart_info)

    #     # 返回总信息结构
    #     result = {
    #         "total": {
    #             "total_cpu": total_cpu,
    #             "total_mem": total_mem
    #         },
    #         "departs_info": departs_info
    #     }

    #     return result
